import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
import { CommService } from './../../comm/comm.service';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import 'rxjs/add/operator/map';
import { Subject } from 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { NgForm } from '@angular/forms';
import { ReportUrls } from '../../comm/report.urls.conf';
import { SubArea } from '../../model/report/sub-area';
import { QueryModel } from '../../model/report/query-model';
import { ResponseModel } from '../../model/comm/response-model';
import { FileUploader } from 'ng2-file-upload';
declare const $: any;
import * as moment from 'moment';
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';
import { DxDataGridComponent } from '../../../../../node_modules/devextreme-angular';
import { Tool } from 'app/ptpmc/model/report/tool';
import { ToolAttachment } from 'app/ptpmc/model/report/tool-attachment';
declare var swal: any;

@Component({
    selector: 'app-tool',
    templateUrl: './toolReport.component.html',
    styleUrls: ['./toolReport.component.css'],
})

export class ToolReportComponent implements OnInit, AfterViewInit {

    @ViewChild(DxDataGridComponent) dataGrid: DxDataGridComponent;
    //excel 文件导入
    public uploader: FileUploader = new FileUploader({
        url: ReportUrls.BaseUrl + ReportUrls.ToolImportUrl,//"http://localhost:3000/ng2/uploadFile",
        method: "POST",
        autoUpload: false,
        itemAlias: "uploader"
    });
    /**查询按类型 */
    // public typeItems = [{ id: 1, text: '按值统计' }, { id: 2, text: '按班次统计' }];
    // public typeSelected = this.typeItems[0];

    //弹出框
    private dialogGrid: Tool = new Tool();

    /*表示设置目标值的Dialog是否打开*/
    public opened = false;
    //查询区
    public queryModel: Tool = new Tool();
    /**选择项 */
    public items: Tool[] = [];
    public selectedItems: Tool[] = [];


    /*生产线 - 班次*/
    public subAreaItems: SubArea[];
    public shiftItems: any[];
    public equipemntItems: TVResource[] = [];
    public versionItems: any[];
    public subAareSelected: any;
    public shiftSelected: any;
    public equipmentSelected: TVResource[] = [];
    public _equipmentSelected: TVResource[] = [];

    //TD
    public drawingVersions: ToolAttachment[] = [];
    public layoutVersions: ToolAttachment[] = [];
    public drawingVersionSelected: any;
    public layoutVersionSelected: any;
    filterVlaueItems: string[] = ['All'];
    addFilterVlaueItemItem(data) {
        var newItem = data.text;
        this.filterVlaueItems.push(newItem)
        return newItem;
    }



    filterChange(data) {
        if (data.value == "All") {
            this.dataGrid.instance.clearFilter();
        } else {
            this.dataGrid.instance.filter(["duration", ">", data.value]);
        }
    }

    constructor(private commServices: CommService) {
    }
    onSubAreaSelectedChange(subArea: SubArea): void {
        this.equipemntItems = this.commServices.getTVResourceBySubArea(subArea.subArea);
        this._equipmentSelected = this.equipemntItems;

    }
    get selectedRows(): TVResource[] {
        return this._equipmentSelected;
    }
    set selectedRows(value: TVResource[]) {
        this._equipmentSelected = value || [];
    }
    ngOnInit() {
        this.queryModel.startToolId = "";
        this.queryModel.endToolId = "";
        this.queryModel.supplierOrderNumber = "";
        this.queryModel.processingProperties = "";
        this.queryModel.version = "";
        this.getReportData();
    }

    ngAfterViewInit() {
    }

    /**获取表格数据*/

    getReportData(): void {
        debugger;


        const url: string = ReportUrls.ToolListUrl;
        debugger;
        this.commServices
            .getList(this.queryModel, url)
            .subscribe(model => {
                this.items = [];
                if (model.resultCode === 200) {
                    debugger
                    this.items = model.data;
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }

    public updateFilterList: Tool[] = [];

    saveChanges() {
        debugger;
        this.commServices.update(this.dialogGrid, ReportUrls.ToolUpdateUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.updateFilterList = [];
                    alert("更新成功！");
                } else {
                    // console.log(model.resultCode + ',' + model.resultMessage);
                    alert('更新失败！' + model.resultMessage);
                }
            });
    }

    /**获取TimeRange的值*/
    getTime(id: any): String {
        const timerange: String = $('#' + id).val();
        return timerange;
    }

    /**Dialog相关*/
    openDialog(itemData: Tool): void {
        this.dialogGrid = itemData;
        $("#filterModal").modal('toggle');
    }
    openDialogDrawing(itemData: Tool): void {
        this.dialogGrid = itemData;
        const attachment: ToolAttachment = new ToolAttachment();
        attachment.suffix = "TD";
        attachment.toolKey = itemData.toolId;
        this.commServices.getList(attachment, ReportUrls.ToolAttachmentVersionsUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.drawingVersions = model.data;
                    this.drawingVersionSelected = this.drawingVersions[0];
                } else {
                    // console.log(model.resultCode + ',' + model.resultMessage);
                    alert('获取失败：' + model.resultMessage);
                }
            });
        $("#filterModalDrawing").modal('toggle');
    }
    openDialogLayout(itemData: Tool): void {
        this.dialogGrid = itemData;
        const attachment: ToolAttachment = new ToolAttachment();
        attachment.suffix = "TL";
        attachment.toolKey = itemData.toolId;
        this.commServices.getList(attachment, ReportUrls.ToolAttachmentVersionsUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.layoutVersions = model.data;
                    this.layoutVersionSelected = this.layoutVersions[0];
                } else {
                    // console.log(model.resultCode + ',' + model.resultMessage);
                    alert('获取失败：' + model.resultMessage);
                }
            });
        $("#filterModalLayout").modal('toggle');
    }
    /**Dialog相关*/
    // public closeDialog(status: any) {
    //     console.log(`Dialog result: ${status}`);
    //     this.opened = false;
    //     if (status === 'yes') {
    //         const file: File = $('input[type=\'file\']')
    //         this.baseServices.updateTool(this.dialogGrid, file);

    //         const file: File = $('input[type=\'file\']')[0].files[0];
    //         this.baseServices.updateTool(this.dialogGrid, file);
    //     }
    // }

    viewLayoutPdf() {
        window.open(`${ReportUrls.BaseUrl + ReportUrls.ToolAttachmentViewUrl}/${this.layoutVersionSelected.fileName}`);
    }
    viewDrawingPdf() {
        window.open(`${ReportUrls.BaseUrl + ReportUrls.ToolAttachmentViewUrl}/${this.drawingVersionSelected.fileName}`);
    }
    downloadTemplate() {
        window.open(ReportUrls.BaseUrl + ReportUrls.ToolTemplateUrl);
    }
    importExcel() {
        // 上传
        this.uploader.queue[0].onSuccess = function (response, status, headers) {
            // 上传文件成功
            let res = JSON.parse(response);
            if (status == 200) {
                // 上传文件后获取服务器返回的数据
                let res = JSON.parse(response);
            } else {
                // 上传文件后获取服务器返回的数据错误
                alert("");
            }
        };
        this.uploader.queue[0].upload(); // 开始上传   
    }
    onExporting(e) {
        e.fileName = e.fileName + new Date().toISOString().replace(/[\-\:\.]/g, '').split('T')[0];
    }
}
